package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.AppUser;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.user.mapper.AppUserMapper;
import com.heima.user.service.AppUserService;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.lang.*;
import java.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {
	@Autowired
	private AppUserMapper appUserMapper;
	//登录服务
	@Override
	public ResponseResult login(LoginDto loginDto) {
		if (!StringUtils.isBlank(loginDto.getPhone()) && !StringUtils.isBlank(loginDto.getPassword())) {
			
			//
			LambdaQueryWrapper<AppUser> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(AppUser::getPhone,loginDto.getPhone());
			
			AppUser appUser = appUserMapper.selectOne(wrapper);
			//用户不存在返回用户不存在错误
			if (appUser == null) {
				return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
			}
			
			//密码校验
			String salt = appUser.getSalt();
			String password = loginDto.getPassword();
			//存储的密码为 : 明文密码
			password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
			
			if (!password.equals(appUser.getPassword())){
				return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
			}else {
				HashMap<String, Object> map = new HashMap<>();
				map.put("token", AppJwtUtil.getToken(appUser.getId().longValue()));
				appUser.setSalt("");
				appUser.setPassword("");
				map.put("user", appUser);
				return ResponseResult.okResult(map);
			}
			
			
		}
		else {
			//2.游客  同样返回token  id = 0
			Map<String, Object> map = new HashMap<>();
			map.put("token", AppJwtUtil.getToken(0L));
			return ResponseResult.okResult(map);
		}
	}
}
